package com.atguigu.gmall.msg.service;

import com.atguigu.gmall.msg.util.HttpUtils;
import com.atguigu.gmall.msg.util.SMSProperties;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class SendMsg {
    @Autowired
    SMSProperties smsProperties;
    //实际使用鼎信第三方发送验证码的方法
    public void proxySendMsg(String mobile,String fourBitRandom) {
        String host = smsProperties.getHost();
        String path = smsProperties.getPath();
        String method = smsProperties.getMethod();
        String appcode = smsProperties.getAppCode();
        String tpl_id = smsProperties.getTpl_id();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("param", "code:"+fourBitRandom);
        querys.put("tpl_id", tpl_id);
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            HttpResponse response = (HttpResponse) HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String responseJson = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("responseJson = " + responseJson);

            Gson gson = new Gson();
            Map map = gson.fromJson(responseJson, Map.class);
            if (Objects.isNull(map)||!"00000".equals(map.get("return_code"))) {
                throw new RuntimeException(map.get("return_code").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
